﻿/* ----------------------------------------------------------------------------
 * Copyright (c) Philip Stears 
 *
 * This source code is subject to terms and conditions of the Microsoft Public 
 * License (Ms-PL).
 * 
 * By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 * 
 * To request a copy of the Microsoft Public License, send a request by email
 * to license@connectbasic.net.
 *
 * This notice must not be removed from this software.
 * ---------------------------------------------------------------------------- */

namespace ConnectBasic.Shell.Hosting.OpenXmlFileProjectStoreInternals
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    internal class ProjectStoreProperties : IProjectStoreProperties
    {
        private XElement mPropertiesElement;
        private Dictionary<string, XElement> mProperties;

        #region .ctor

        internal ProjectStoreProperties(XElement propertiesElement)
        {
            mPropertiesElement = propertiesElement;

            // Convert the properties element into 
            // a dictionary which maps the property name
            // onto the property element
            mProperties =
                propertiesElement
                .Elements(propertiesElement.Name.Namespace + "Property")
                .ToDictionary(
                    (propElement) => propElement.Attribute("Name").Value,
                    StringComparer.OrdinalIgnoreCase);

        }

        #endregion

        #region IProjectStoreProperties Members

        public string GetPropertyText(string name)
        {
            XElement propertyElement;

            if (mProperties.TryGetValue(name, out propertyElement))
            {
                return propertyElement.Value;
            }
            else
            {
                return null;
            }
        }

        public void SetPropertyText(string name, string text)
        {
            if (name == null) throw new ArgumentNullException("name");

            if (text == null)
            {
                mProperties.Remove(name);
            }
            else
            {

                // Try getting the existing properties, and failing that
                // create a new one
                XElement propertyElement;
               
                if (!mProperties.TryGetValue(name, out propertyElement))
                {
                    propertyElement = new XElement(mPropertiesElement.Name.Namespace + "Property");
                    mPropertiesElement.Add(propertyElement);
                    mProperties.Add(name, propertyElement);
                }

                // Set its value
                propertyElement.Value = text;
            }
        }

        #endregion
    }
}
